using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Rules;

namespace Golf.WebUI.Controllers
{
    using Core;
    using DataLayer;    
    using Models;

    public class PlayerController : Controller
    {
        public ActionResult Details(int id)
        {
            Player player = PlayerRepository.Get(id);
            return View(player);
        }

        public ActionResult Edit(int id)
        {
            Player player = PlayerRepository.Get(id);
            EditPlayerViewModel model = new EditPlayerViewModel(player, CountyRepository.GetAll());
            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ActionName("Edit")]
        public ActionResult Update(int id)
        {
            Player player = PlayerRepository.Get(id);
            TryUpdateModel<Player>(player);
            Validate(player);
            if (ModelState.IsValid)
            {
                new PlayerRepository().Save(player);
                return RedirectToAction("Edit", new { id = player.Id });
            }
            return View(new EditPlayerViewModel(player, CountyRepository.GetAll()));
        }

        public ActionResult Create()
        {
            EditPlayerViewModel model = new EditPlayerViewModel(new Player(), CountyRepository.GetAll());
            return View("Edit", model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ActionName("Create")]
        public ActionResult Insert()
        {
            Player player = new Player();
            TryUpdateModel<Player>(player);
            PlayerRepository.Save(player);
            return RedirectToAction("Edit", new { id = player.Id });
        }

        private void Validate(Player player)
        {
            List<IRule> rules = new List<IRule>();
            rules.Add(new StringLengthRule(2, 50, "Forename"));
            rules.Add(new StringLengthRule(2, 50, "Surname"));
            RuleCollection brokenRules = new RuleCollection(rules).Evaluate<Player>(player);
            foreach (IRule brokenRule in brokenRules)
            {
                ModelState.AddModelError(brokenRule.PropertyName, brokenRule.Description);
            }
        }

        private PlayerRepository _playerRepository = new PlayerRepository();
        private PlayerRepository PlayerRepository
        {
            get { return _playerRepository; }
        }

        private CountyRepository _countyRepository = new CountyRepository();
        private CountyRepository CountyRepository
        {
            get { return _countyRepository; ; }
        }
     }
}